# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter

''' 处理爬虫数据的管道类，保存数据为CSV格式文件 '''

import spider.utils as utils


class CSVPipeline:

    def __init__(self):
        self.fileName = ''
        self.printHeader = False
        self.f = None

    def open_spider(self, spider):
        self.fileName = spider.settings.get('DOWNLOAD_FILE_NAME').format(spider.name)
        self.f = open(self.fileName, 'w+', encoding='utf-8')

    def process_item(self, item, spider):
        if not self.printHeader:
            self.f.write(utils.getCSVHeader(item))
            self.printHeader = True
        self.f.write(utils.objectToCSV(item))
        return item

    def close_file(self):
        self.f.close()
